package com.adu.music.spider;

import com.adu.music.api.MusicApi;
import com.adu.music.bean.PlaylistCategory;
import com.adu.music.util.JsoupUtils;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author duchuanchuan
 * @date 2017/1/1
 */
public class PlaylistNewSpider extends AbstractSpider {
    // 歌单种类
    private final List<String> categories = new ArrayList<>();
    private int pageIndex = 0;

    /**
     * 初始化歌单种类
     */
    private void initCategories() {
        MusicApi.initPlayListcxCategories(categories);
    }

    private List<PlaylistCategory> queryByIndex(int index) throws IOException {
        String cate = categories.get(index);
        String encCate = URLEncoder.encode(cate, "UTF-8");
        String url = "http://music.163.com/discover/playlist/?cat=" + encCate;
        PlaylistCategory category = new PlaylistCategory(encCate, 0);
        List<PlaylistCategory> playlistCategories = new ArrayList<>();
        playlistCategories.add(category);
        Optional<Document> docOptional = JsoupUtils.get(url);
        docOptional.ifPresent(doc -> {
            Elements elements = doc.getElementsByClass("zpgi");
            String lastPage = elements.get(elements.size() - 1).text();
            int lastPageIndex = Integer.parseInt(lastPage);
            for (int i = 1; i < lastPageIndex; i++) {
                playlistCategories.add(new PlaylistCategory(encCate, 35 * i));
            }
        });
        return playlistCategories;
    }

    @Override
    protected void initTaskQueue() {
        initCategories();
        addTaskToQueue();
    }

    private void addTaskToQueue() {
        try {
            List<PlaylistCategory> playlistCategories = queryByIndex(pageIndex);
            playlistCategories.forEach(this::putTaskToQueue);
            pageIndex++;
        } catch (IOException e) {
            logger.error("查询歌单类型异常, pageIndex: {}", pageIndex);
            e.printStackTrace();
        }
    }

    @Override
    protected void produceTask() {
        while (pageIndex < categories.size()) {
            addTaskToQueue();
        }
    }

    @Override
    protected void consumeTask(Object task) {
        final String sql = "insert into playlist(id,name,category,favorite,share,comment,play,description,user_id,user_name) " +
                "values(:id,:name,:category,:favorite,:share,:comment,:play,:description,:user_id,:user_name) " +
                "ON DUPLICATE KEY UPDATE favorite=values(favorite),share=values(share),comment=values(comment),play=values(play),updated_at=now()";
        PlaylistCategory category = (PlaylistCategory) task;
        List<Map<String, Object>> list = MusicApi.crawlHotPlayLists(category);
        if (!list.isEmpty()) {
            list.forEach(map -> asyncNamedParameterJdbcTemplate.update(sql, map));
        }
    }
}
